# -*- coding: utf-8 -*-
import base64
import hashlib
import json
import time
from collections import OrderedDict

from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '12518': {  # dwc 支付宝
        'API_KEY': '9f8917098e314fbabdee80898320ed39',
        'gateway': 'https://www.c3x0.cn/api/dandanpay/index?data={}',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


# 将私钥，时间戳，充值金额，用户订单号，商户id md5加密。
def generate_sign(d, key):
    s = key + d['Time'] + d['Amount'] + d['OrderNo'] + d['MerchantId']
    _LOGGER.info("dandanpay sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['Sig']
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("dandanpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('Time', str(int(time.time()))),
        ('MerchantId', app_id),
        ('NotifyUrl', '{}/pay/api/{}/dandanpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('OrderNo', str(pay.id)),
        ('Amount', str(pay_amount)),
        ('Subject', 'charge'),
        ('Info', 'charge'),
    ))
    parameter_dict['Sig'] = generate_sign(parameter_dict, api_key)
    j = json.dumps(parameter_dict)
    data = base64.b64encode(j)
    url = _get_gateway(app_id).format(data)
    _LOGGER.info("dandanpay create: %s, %s, url: %s", j, data, url)
    return {'charge_info': url}


# 1
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("dandanpay notify data: %s", data)
    data['MerchantId'] = app_id
    verify_notify_sign(data, api_key)
    pay_id = data['OrderNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('dandanpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = 'success'
    trade_no = data['TradeNo']
    total_fee = float(data['Amount'])
    discount = float(json.loads(pay.extend or '{}').get('discount', 0))
    extend = {
        'discount': discount,
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 'success':
        _LOGGER.info('dandanpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pass
